module FluentConditions
  class ConditionBuilder
    def initialize(object, type)
      @object = object
      @type = type
      @previous, @current, @big_or = true, true, false
    end

    def or
      @or_used = true
      self
    end

    def OR
      update_big_or_result
      @big_or_used = true
      self
    end

    def AND
      self
    end

    def and
      self
    end

    private

    def update_and_continue(field_value)
      update_current_result(field_value)
      self
    end

    def update_and_finish(field_value)
      update_current_result(field_value)
      update_big_or_result if @big_or_used
      end_result
    end

    def update_current_result(field_value)
      if @or_used
        @current = @current || field_value
        @or_used = false
      else
        @previous, @current = @previous && @current, field_value
      end
    end

    def update_big_or_result
      @big_or = @big_or || current_result
      @previous, @current = true, true
    end

    def current_result
      @previous && @current 
    end

    def end_result
      @type == :positive ? sub_result : !sub_result
    end

    def sub_result
      @big_or_used ? @big_or : current_result
    end

  end
end
